#include "shelf.h"

Shelf::Shelf(int maxSize, QObject *parent) :
    maxSize(maxSize), QObject(parent)
{
    mutex = new QMutex();
}

void Shelf::takeBook(int pos){
    books[pos]->lock();
}

void Shelf::putBook(int pos){
    books[pos]->unlock();
}

void Shelf::putNewBook(int pos){
    books[pos]->unlock();
    emit newBook();
}

int Shelf::tryWriteNewBook()
{
    mutex->lock();
    if(books.size() >= maxSize) {
        mutex->unlock();
        return -1;
    }

    int bookIndex = books.size();
    books.push_back(new QMutex());
    books[books.size()-1]->tryLock();
    mutex->unlock();
    return bookIndex;
}

int Shelf::size()
{
    return books.size();
}


